#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <malloc.h>

#include <gccore.h>
#include <sdcard/wiisd_io.h>
#include "gecko_console.h"

static GXRModeObj *rmode = NULL;
static u32 *xfb = NULL;

int main(int argc, char *argv[])
{
	VIDEO_Init();
	PAD_Init();
	
	rmode = VIDEO_GetPreferredMode (NULL);
	VIDEO_Configure (rmode);

	xfb = MEM_K0_TO_K1(SYS_AllocateFramebuffer(rmode));
	VIDEO_ClearFrameBuffer(rmode,xfb,COLOR_BLACK);
	VIDEO_SetNextFramebuffer(xfb);
	VIDEO_SetBlack(FALSE);
	VIDEO_Flush();
	VIDEO_WaitVSync();
	
	if(rmode->viTVMode&VI_NON_INTERLACE) VIDEO_WaitVSync();
	
	CON_InitEx(rmode, 20,30,rmode->fbWidth-40,rmode->xfbHeight-60);
	gecko_console_init(1);

	printf("hint: this will destroy your sd card's filesystem.\n");
	printf("hint #2: if you are reading this it's too late now to save your data...\n");

	int fd;

	fd = IOS_Open("/dev/flash", 0);
	if(fd < 0)
	{
		printf("/dev/flash: %d\n", fd);
		return 0;
	}

	if(sdio_Startup() == false || sdio_IsInserted() == false)
	{
		printf("sd card init failed.\n");
		return 0;
	}

	printf("dumping 4096 blocks now..\n");

	int i, j, k, ret;
	void *ptr = memalign(32, 64 * (2048 + 64));
	void *tmp = memalign(32, 2048 + 64);

	for(i = 0; i < 4096; i++)
	{
		if(i % 50 == 0)
			printf("block %d\n", i);
		memset(ptr, 0xaa, 64 * (2048 + 64));
		for(j = 0; j < 8; j++)
		{
			for(k = 0; k < 8; k++)
			{
				ret = IOS_Seek(fd, (i*64) + (j*8) + k, 0);
//				if(ret < 0)
//					printf("seek = %d\n", ret);
				memset(tmp, 0xaa, (2048 + 64));
				ret = IOS_Read(fd, tmp, 2048+64);
				memcpy(ptr + (j * 8 * (2048 + 64)) + k * (2048 + 64), tmp, 2048+64);
//				if(ret < 0)
//					printf("read = %d\n", ret);
			}
		}
		sdio_WriteSectors(i * 264, 264, ptr);
	}

	return 0;
}
